package com.ckzp.jfinal.base;

import cn.hutool.core.collection.CollUtil;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

import java.util.List;

/**
 * Created by 51594 on 2024/5/2.
 */
public class DataModel {

    private Record record;

    private String table_name = "";

    public DataModel() {
        if (record == null) record = new Record();
    }

    public String getTable_name() {
        return table_name;
    }

    public DataModel setTable_name(String table_name) {
        this.table_name = table_name;
        return this;
    }

    public DataModel setRecord(Record record) {
        this.record = record;
        return this;
    }

    public DataModel(Record record) {
        this.record = record;
    }

    public static DataModel n() {
        return new DataModel();
    }

    public static DataModel n(Record record) {
        return new DataModel(record);
    }

    public static DataModel n(String table_name) {
        return new DataModel().setTable_name(table_name);
    }

    public DataModel set(String column, Object value) {
        record.set(column, value);
        return this;
    }

    public <T> T get(String column) {
        return record.get(column);
    }

    public <T> T get(String column, Object defaultValue) {
        return record.get(column, defaultValue);
    }

    /**
     * 查询第一个
     *
     * @param column
     * @param value
     * @return
     */
    public DataModel findFirst(String column, Object value) {
        this.record = Db.findFirst("select * from " + table_name + " where " + column + " =?", value);
        return this;
    }

    /**
     * @param sql
     * @return
     */
    public List find(String sql) {
        List listnew = CollUtil.newArrayList();
        for (Record rec : Db.find(sql)) {
            listnew.add(DataModel.n(rec));
        }
        return listnew;
    }


    public String toJson() {
        return record.toJson();
    }

    /**
     * 保存
     */
    public boolean save() {
//        System.out.println(table_name);
//        System.out.println(record.toJson());
      return   Db.save(this.table_name, record);
//        System.out.println(record.toJson());
    }
}
